import { HNSWLib } from "@langchain/community/vectorstores/hnswlib";
import { OpenAIEmbeddings } from "@langchain/openai";
import { Document } from "@langchain/core/documents";
import "dotenv/config";

// 示例文档
const docs = [
  new Document({
    pageContent: "LangChain is a framework for building LLM applications.",
  }),
  new Document({
    pageContent: "HNSWLib is a fast nearest neighbor search library.",
  }),
  new Document({ pageContent: "OpenAI provides powerful language models." }),
];

// 创建向量数据库
const vectorStore = await HNSWLib.fromDocuments(
  docs,
  new OpenAIEmbeddings({
    configuration: {
      apiKey: process.env.OPENAI_API_KEY,
      baseURL: process.env.OPENAI_API_BASE,
    },
  }) // 你也可以换成别的 embedding 模型
);

// 保存到本地（可选）
await vectorStore.save("hnsw_index");

// 载入向量库（如果已有保存）
const loadedStore = await HNSWLib.load(
  "hnsw_index",
  new OpenAIEmbeddings({
    configuration: {
      apiKey: process.env.OPENAI_API_KEY,
      baseURL: process.env.OPENAI_API_BASE,
    },
  })
);

// 查询
const results = await loadedStore.similaritySearch("What is LangChain?", 2);
console.log("Top results:");
results.forEach((r, i) => {
  console.log(`Result ${i + 1}:`, r.pageContent);
});
